package com.Txunda.fxw.ui.activity.law;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.util.JSONUtils;
import com.Txunda.fxw.base.utils.util.MapUtils;
import com.Txunda.fxw.ui.base.BaseAty;
import com.Txunda.fxw.ui.http.Office;
import com.Txunda.fxw.ui.toolkit.util.PreferenceUtil;
import com.Txunda.fxw.ui.widget.XCRoundAndOvalImageView;
import com.bumptech.glide.Glide;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 法律咨询
 *
 * @author Administrator
 */
public class Legal_AdviceAty extends BaseAty {


    @BindView(R.id.aty_title3_icon)
    ImageView atyTitle3Icon;
    @BindView(R.id.aty_title3_tv_center)
    TextView atyTitle3TvCenter;
    @BindView(R.id.aty_title3_tv_right2)
    TextView atyTitle3TvRight2;
    @BindView(R.id.tv_content_legal)
    WebView tvContentLegal;
    @BindView(R.id.linear_img)
    LinearLayout linearImg;
    @BindView(R.id.legal_lv)
    PullToRefreshListView legalLv;
    @BindView(R.id.icon_no_data_iv)
    ImageView iconNoDataIv;
    private List<Map<String, String>> list_data;
    private MyAdapter adapter;

    private Office office;
    private int p = 1;

    private Bundle bundle;
    private String district;
    private List<Map<String, String>> list_more_data;

    private String city_name;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        district = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_district);
        String area_name = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_mode);

        tvContentLegal.getSettings().setJavaScriptEnabled(true);
        tvContentLegal.getSettings().setDefaultTextEncodingName("utf-8");
        tvContentLegal.setBackgroundColor(0); // 设置背景色
        tvContentLegal.getBackground().setAlpha(0); // 设置填充透明度 范围：0-255
        tvContentLegal.loadDataWithBaseURL(null, "加载中。。", "text/html", "utf-8", null);
        tvContentLegal.setVisibility(View.VISIBLE); // 加载完之后进行设置显示，以免加载时初始化效果不好看

        String district_id = getIntent().getStringExtra("district_id");
        city_name = getIntent().getStringExtra("city_name");    //城市名称
        if (district_id == null || district_id.equals("")) {
            showProgressDialog();
            office.personList(district, p, area_name, this);
            atyTitle3TvRight2.setText(area_name);
        } else {
            showProgressDialog();
            office.personList(district_id, p, city_name, this);
            atyTitle3TvRight2.setText(district_id);
        }


        legalLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                p = 1;
                showProgressDialog();
                office.personList(district, p, city_name, Legal_AdviceAty.this);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                p++;
                showProgressDialog();
                office.personList(district, p, city_name, Legal_AdviceAty.this);
            }
        });
        legalLv.onRefreshComplete();


        legalLv.setEmptyView(iconNoDataIv);

        legalLv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bundle = new Bundle();
                bundle.putString("p_id", list_data.get(position - 1).get("p_id"));
                startActivity(LegalAdviceAty.class, bundle);
            }
        });
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.aty_legal__advice;
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
        if (MapUtils.isEmpty(map))
            return;
        if (requestUrl.contains("personList")) {    //律师列表
            Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
            if (MapUtils.isEmpty(data))
                return;
            String content = data.get("content");
            String img = data.get("img");
            new DownloadImageTask().execute(img);
            tvContentLegal.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
            //tv_content_legal.setText(content);
            if (!data.get("list").equals("null") && data.get("list") != null) {
                if (p == 1) {
                    list_data.clear();
                    list_data = JSONUtils.parseKeyAndValueToMapList(data.get("list"));
                    legalLv.setAdapter(adapter);
                } else {
                    list_more_data = JSONUtils.parseKeyAndValueToMapList(data.get("list"));
                    list_data.addAll(list_more_data);
                    adapter.notifyDataSetChanged();
                }
            }
            legalLv.onRefreshComplete();
        }
    }

    @Override
    public void onError(String requestUrl, Map<String, String> error) {
        super.onError(requestUrl, error);
        legalLv.onRefreshComplete();
    }

    @Override
    protected void initialized() {
        list_more_data = new ArrayList<>();
        office = new Office();
        list_data = new ArrayList<>();

        atyTitle3TvCenter.setText("律师法律咨询");
        atyTitle3TvRight2.setVisibility(View.VISIBLE);

        list_data = new ArrayList<>();
        adapter = new MyAdapter();
    }

    @SuppressLint("StaticFieldLeak")
    private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
            linearImg.setBackgroundDrawable(result);
        }
    }

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过第二个参数(文件名)来判断，是否本地有此图片
            drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
        } catch (IOException e) {
            Log.d("skythinking", e.getMessage());
        }
        if (drawable == null) {
            Log.d("skythinking", "null drawable");
        } else {
            Log.d("skythinking", "not null drawable");
        }

        return drawable;
    }

    @Override
    protected void requestData() {

    }

    /**
     * 法律咨询adapter
     *
     * @author Administrator
     */
    public class MyAdapter extends BaseAdapter {

        MyViewHolder vh;

        @Override
        public int getCount() {
            int ret = 0;
            if (list_data != null) {
                ret = list_data.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            return list_data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(Legal_AdviceAty.this).inflate(R.layout.item_layout_legal, parent, false);
                vh = new MyViewHolder();
                ViewUtils.inject(vh, convertView);
                convertView.setTag(vh);
            } else {
                vh = (MyViewHolder) convertView.getTag();
            }
            vh.tv_law_name.setText(list_data.get(position).get("name"));  //律师姓名
            final String pic = list_data.get(position).get("pic");   //头像
            String d_pic = list_data.get(position).get("d_pic");   //地区丝带
            Glide.with(Legal_AdviceAty.this).load(d_pic).into(vh.item_img);

            String wechat = list_data.get(position).get("wechat");
            if (wechat == null || wechat.equals("")) {
                vh.tv_law_weixin.setVisibility(View.GONE);
            } else {
                vh.tv_law_weixin.setText(list_data.get(position).get("wechat"));    //微信
            }
            String qq = list_data.get(position).get("qq");
            if (qq == null || qq.equals("")) {
                vh.tv_law_qq.setVisibility(View.GONE);
            } else {
                vh.tv_law_qq.setText(list_data.get(position).get("qq"));   //qq
            }
            String tel = list_data.get(position).get("tel");
            if (tel == null || tel.equals("")) {
                vh.tv_law_phone.setVisibility(View.GONE);
            } else {
                vh.tv_law_phone.setText(list_data.get(position).get("tel"));   //电话
            }
            vh.tv_law_lo.setText(list_data.get(position).get("z_name"));    //执业机构
            vh.item_legal_area.setText(list_data.get(position).get("district_name"));   //地区

            vh.item_legal_img.setType(XCRoundAndOvalImageView.TYPE_ROUND);
            vh.item_legal_img.setRoundRadius(150);
            Glide.with(Legal_AdviceAty.this).load(pic).into(vh.item_legal_img);
            return convertView;
        }


        class MyViewHolder {
            @ViewInject(R.id.tv_law_name)
            private TextView tv_law_name;
            @ViewInject(R.id.tv_law_ho)
            private TextView tv_law_lo;  //执业机构
            @ViewInject(R.id.tv_law_wexin)
            private TextView tv_law_weixin;
            @ViewInject(R.id.tv_law_qq)
            private TextView tv_law_qq;
            @ViewInject(R.id.tv_law_phone)
            private TextView tv_law_phone;
            @ViewInject(R.id.item_legal_img)
            private XCRoundAndOvalImageView item_legal_img; //头像
            @ViewInject(R.id.item_legal_area)
            private TextView item_legal_area;   //地区
            @ViewInject(R.id.item_img)
            private ImageView item_img;
            //@ViewInject(R.id.linear_law)
            //private LinearLayout linear_law;

        }
    }
}
